#include "Daddy.h"


Daddy::Daddy(void)
{
	Instrument::Instrument();

	//DigitalOffset = 2048;
	//DigitalMax = 4096;
	//DigitalMin = 0;
	//Resolution = 1;
	
	DigitalOffset = 0;
	DigitalMax = 1024;
	DigitalMin = 0;
	Resolution = 1;
		
	MyName = _("Daddy");
	Initialize(8,128,20);
	
	pDev = NULL;
}

Daddy::~Daddy(void)
{
	if(pDev != NULL)
	{
		delete pDev;
		pDev = NULL;
	}
}

static void Scompatta(char *DataIn, UINT *Channel, UINT *Data)
{
	_int16 Canale,Hi,Low;

	Canale		=	(DataIn[0] & 0xE0)	>> 5;
	Hi			=	(DataIn[0] & 0x1F);
	Hi			=	Hi << 7;
	Low			=	DataIn[1] & 0x7F;
	*Channel	=	Canale;
	*Data		=	Hi | Low;
}
static bool ScompattaBlocco(char *DataIn,HimDataStruct *pOut)
{
	int i;
	UINT Dout,Ch;
	for(i = 0; i<8;i++)
	{
		Scompatta(&DataIn[i*2],&Ch,&Dout);
		if(Ch == i) pOut->Signal[i] = Dout;
		else return false;
	}
	return true;
}

void* Daddy::Entry(void)
{
	bool		SynchOk = false;
	int			Dim;
	int			read;
	char		Buffer[16];//,2*ch;
	SampleStruct	Signal;
	memset(&Signal,0,sizeof(Signal));
	Signal.Data.DataLen	=	Channels;

	Esci = false;
	while(!Esci)
	{
		Dim = 16;
		read = 0;
		if(IsRunning)
		{
			do{
				do{
					read += pDev->Read(&Buffer[read],Dim-read);
					if(read < 16) Sleep(4);
				}while(read < Dim && !Esci);

				if(ScompattaBlocco(Buffer,&Signal.Data))
				{
					SynchOk = true;
				}else
				{
					IncErrorCounter();
					SynchOk = false;
					memcpy(Buffer,&Buffer[1],15);
					read = 15;
				}
			}while(!SynchOk && !Esci);
			if(!Esci)	PutSample(&Signal);
		}else Sleep(100);

	}


	StopDevice();
	Sleep(100);
	pDev->Close();
	
	/*if(pDataSaver != NULL)
	{
		//pDataSaver->Close();
		delete pDataSaver;
		pDataSaver = NULL;
	}*/

	return NULL;
}
void Daddy::StartDevice(wxString FileName,wxString FilePath,bool File)
{
	Instrument::StartDevice(FileName,FilePath,File);
	char ch = 's';
	if(!IsRunning)
	{
		IsRunning	=	true;
		if(pDev !=NULL)		pDev->Write(&ch,sizeof(char));
	}
}
void Daddy::StopDevice(void)
{
	char ch = 't';
	if(IsRunning)
	{
		IsRunning	=	false;
		if(pDev !=NULL)		pDev->Write(&ch,sizeof(char));
		Instrument::StopDevice();
	}
}
int Daddy::OpenPort(const char *PortName, const char *OpenVal2, const char *OpenVal3)
{
	wxBaud baudrate = wxBAUD_115200;

	if(pDev == NULL)	pDev = new wxSerialPort();
	if(pDev->Open(PortName) < 0)
	{
		return -1;	
	}
	pDev->SetBaudRate(baudrate);
	return 1;
}